package model.fshare.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;

import model.roomManagement.Implementation.Server;
import model.roomManagement.Interface.IDBC;

public class FileReceiver implements Runnable
{
	private Socket dataSource;
	private String fileName;
	private int roomId;
	private int updaterId;
	
	public FileReceiver(Socket socket, int roomId, int updaterId, String fileName)
	{
		dataSource = socket;
		this.fileName = fileName;
		this.roomId = roomId;
		this.updaterId = updaterId;
	}
	
	@Override
	public void run()
	{
		File fileToSave = new File( "SharedFiles/" + roomId + "/" + fileName );
		try 
		{
			fileToSave.getParentFile().mkdirs();
			fileToSave.createNewFile();
			
			DataOutputStream fileWriter = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( fileToSave ) ) );

			DataInputStream dataReader = new DataInputStream( new BufferedInputStream( dataSource.getInputStream() ) );
			
			byte[] buf = new byte[1024];
			int bytesReaded = 0;
			try
			{
				while( (bytesReaded = dataReader.read(buf)) != -1 )
				{
					fileWriter.write( buf, 0, bytesReaded );
					fileWriter.flush();
				}
			}
			catch (Exception e)
			{
				if ( fileToSave.exists() )
				{
					fileToSave.delete();
				}
				e.printStackTrace();
			}
			
			fileWriter.close();
			dataSource.close();
			
			// Call server service
			// File has been received  
			// Server.getDB  db.addFile(File,fileRoom,ownerId )
			IDBC idbc = Server.getDB();
			idbc.addFile( fileToSave, roomId, updaterId );

		}
		catch ( Exception e ) 
		{
			// When exception happended,
			// delete the imcomplete local file.
			if ( fileToSave.exists() )
			{
				fileToSave.delete();
			}
			e.printStackTrace();
		}
	}
	
}
